<template>
    <div>
       
        <div class="signature">
             <span @click="openDialog"  v-if="url == null || url == ''" type="text">手写签名</span>
             <el-image v-else @click="openDialog"  style="height: 50rpx; width:150px;" :src=" baseurl + src" fit="cover">
                    <div slot="error" class="image-slot">
                        <span   @click="openDialog">加载失败，点击重写</span>
                    </div>
             </el-image>
             <div class="op">
                <!-- <span  v-if="url != null && url != '' " @click="openDialog">
                    重写
                </span> -->
             
             </div>
        </div>

        <el-dialog
            class="pane"
            :show-close="false"
            :visible.sync="dialogVisible"
            width="900px"
            @opened="openedHandle"
          >
            <div slot="title" class="pane-title">
                <div class="tool-bar">
                    <i class="el-icon-edit "  :style="{color:isClear==false?'red':''}" @click="draw"></i>
                    <i class="el-icon-brush" :style="{color:isClear==true?'red':''}" @click="setClear"></i>
                    <i class="el-icon-arrow-left" @click="backStep"></i>
                    <i class="el-icon-arrow-right" @click="nextStep"></i>
                    <i class="el-icon-delete" @click="clearAll"></i>
                </div>
                <div class="close" v-if="!disabled">
                    <span @click="upload">
                        保存
                    </span>
                    <span @click="dialogVisible = false">
                        关闭
                    </span>
                </div>
            </div>
            <div class="pane-box">
                <canvas ref="canvas" width="900px" height="300px"></canvas>
            </div>
           
            </el-dialog>

    </div>
</template>

<script>
import {commonUpload} from "@/api/affix/affix"
import { getToken } from "@/utils/auth";
export default {
    name: 'CmSignature',
    inject: {
        elForm: {
            default: '',
          
          
            
        }
    },
    data() {
        return {
            cvs:null,
            ctx:null,
            isClear:false,
            canvasHistory:[],
            step:-1,
            dialogVisible:false,
            baseurl: process.env.VUE_APP_BASE_API ,
            
            uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            src:null,
             baseurl: process.env.VUE_APP_BASE_API ,
            
        }
    },
    props: {
        
        url:{
          type:String,
          default:null,
        },
        disabled:{
            type:Boolean,
            default:false
        }
    },

    methods: {
        upload(){
            let _this = this;
            this.cvs.toBlob(function (blob) {
                // 创建一个File对象
                let f = new File([blob], 'signature.webp', { type: 'image/webp'})
        

                // 图片ajax上传，字段名是image
                commonUpload({file:f}).then(res=>{
                   if(res.code == 200 && res.fileName){
                        //上传成功的文件名
                        _this.$emit("save-success",res.fileName);
                        _this.dialogVisible = false;
                   }
                })
               
            });
        },
        draw(){
            this.isClear = false;
        },
        backStep(){
            if (this.step >= 0) {
                this.step--;
                this.ctx.clearRect(0, 0, this.cvs.width, this.cvs.height);
                let canvasPic = new Image();
                canvasPic.src = this.canvasHistory[this.step];
                canvasPic.addEventListener('load', () => {
                    this.ctx.drawImage(canvasPic, 0, 0);
                });
            }
        },
        nextStep(){
            if (this.step < this.canvasHistory.length - 1) {
                this.step++;
                this.ctx.clearRect(0, 0, this.cvs.width, this.cvs.height);
                let canvasPic = new Image();
                canvasPic.src = this.canvasHistory[this.step];
                canvasPic.addEventListener('load', () => {
                    this.ctx.drawImage(canvasPic, 0, 0);
                });
            }
        },
        setClear(){
            this.isClear = true;
        },
        openedHandle(){
            let _this = this;
            let cvs = this.$refs.canvas;
            if(this.url!=null && this.url != ''){
                let img = new Image();
                img.onload = function() {
                    ctx.drawImage(img, 0, 0); // 在Canvas上绘制图片
                };
                img.src = this.baseurl + this.url; // 替换为你的图片路径
            }
            this.cvs = cvs;
            //获取画笔
            let ctx = cvs.getContext('2d');
            this.ctx = ctx;
            // ctx.translate(0.5, 0.5)
            ctx.lineWidth = 3;
            ctx.lineCap = "round";
            ctx.lineJoin = "round";
            ctx.fillStyle="#ff0000";
            //鼠标按下时间
            cvs.onmousedown = (e)=>{
                //
                ctx.beginPath();
                ctx.moveTo(e.offsetX,e.offsetY);
                cvs.onmousemove = (ev)=>{
                    if(this.isClear){
                        //橡皮擦
                        ctx.clearRect(ev.offsetX-5,ev.offsetY-5,10,10);
                    }else{
                        //画线
                        ctx.lineTo(ev.offsetX,ev.offsetY);
                        ctx.stroke();
                    }
                   
        
                }

            }
            cvs.onmouseup=()=>{
                cvs.onmousemove = null
                _this.step++;
                _this.canvasHistory.push(cvs.toDataURL());
            };
      
        },
        openDialog(){
            this.dialogVisible = true;
   
          
        },
        clearAll(){
            this.step = -1;
            this.canvasHistory = [];
            this.ctx.clearRect(0,0,this.cvs.width,this.cvs.height);
        }
    },
    created() {

 
          
    },
    watch: {
        // 父组件值监听事件
        url: {
            handler: function(newVal/*, oldVal*/) {
                console.log(newVal);
                this.src = newVal;
            }
        }
    },
}
</script>

<style scoped>
.pane>>>.el-dialog__header,.pane>>>.el-dialog__body{
    padding: 0;
}
.pane-title{
    height: 46px;
   

    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
.tool-bar{
    display: flex;
    flex-direction: row;
    justify-content: start;
    gap: 10px;
    align-items: center;
}
.pane-title i{
    width: 46px;
    height: 46px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}
.close{
    display: flex;
    flex-direction: row;
    justify-content: start;
    align-items: center;

}
.close span{
    padding: 10px;
}
.active{
    color: #409EFF;
}
.signature{
    color: #409EFF;
    cursor: pointer;
}
.op{
    display: none;
}
.signature:hover>.op{
    display: block;
}
</style>
